var loggedInUsersEmail;
var messageID;

function getMessageIDFromExtractorMatches(matches) {
    var messageID;
    for (var match in matches) {
        for (var key in matches[match]) {
            if (key == 'message_id') {
                //Stores the message id from the email thread
                messageID = matches[match][key];
            }
        }
    }
    return messageID;
}

function checkFiledStatus() {
    var site = getSiteCode();

    var params = {};
    var encodedEmail = encodeURIComponent(loggedInUsersEmail);
    var url = baseUri + 'oscarfiler/file/status/email/' + encodedEmail + '/messageID/' + messageID + '/site/' + site;

    makeCachedRequest(url, filedResponse, params, 10);
}

function getJobNumberText() {
	return document.getElementById('inputbox').value.replace(/\s/g, "");
}

function fileAgainstJob() {
    setFileComponentsVisibility(false);
    var params = getFileJobPostParams();

    var url = baseUri + 'oscarfiler/file/filejob';
    makeCachedRequest(url, fileAgainstJobResponse, params, 1);

    var paragraph = document.getElementById('validationResponse');
    paragraph.innerHTML = 'Filing...';
}

function getFileJobPostParams() {
	var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.HEADERS] = {'Content-Type': 'application/json'};
    params[gadgets.io.RequestParameters.POST_DATA]= getFileJobPost();
    return params;
}

function getFileJobPost() {
	var jobno = getJobNumberText();
	var actionType = getActionTypeEnumString();
	var site = getSiteCode();
	var fileType = getFileTypeEnumString();
	var selectedAttachments = getSelectedAttachments();

	var json = {
			"siteCode": site,
			"userEmail": loggedInUsersEmail,
			"jobNumber": jobno,
			"messageID": messageID,
			"actionType": actionType,
			"direction": fileType,
			"selectedIndices": selectedAttachments
	};

	return gadgets.json.stringify(json);
}

function getSelectedAttachments() {
	var filenamesSelected = [];

    var table = document.getElementById("tblAttachments");
    if (table != null) {
        for (var i = 0; i < table.rows.length; i++) {
            if (table.rows[i].cells[1].innerHTML.toString().indexOf('name="on"') != -1) {
                filenamesSelected.push(i);
            }
        }
    }
    return filenamesSelected;
}

function getSiteCode() {
    return document.getElementById("siteCode").innerHTML;
}

function getActionTypeEnumString() {
    var e = document.getElementById("actionrequested");
    var action = e.options[e.selectedIndex].text;

    if (action === 'Urgent Action') {
        return 'URGENT_ACTION_REQUIRED';
    }
    else if (action === 'Standard Action') {
        return 'STANDARD_ACTION_REQUIRED';
    }
    return 'NO_ACTION_REQUIRED';
}

function getFileTypeEnumString() {
    var e = document.getElementById("filetype");
    var type = e.options[e.selectedIndex].text;

    if (type === 'Inbound') {
        return 'IN_BOUND';
    }
    return 'OUT_BOUND';
}

function handleClick(cb) {
    if (cb.checked) {
        cb.name = 'on';
    }
    else {
        cb.name = 'off';
    }
}

function addAttachmentFilenamesToTable(response) {
    if (response.filenames.length > 0) {
        var table = document.createElement("table");
        table.setAttribute('id', 'tblAttachments');

        for (var i = 0; i < response.filenames.length; i++) {
            var row = table.insertRow(i);

            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);

            var inline = gadgets.json.parse(response.filenames[i].inline);
            var valid = gadgets.json.parse(response.filenames[i].validAttachment);
            cell1.innerHTML = response.filenames[i].name;
            cell1.className = 'filename';
            var checked = '';
            var name = '"off"';
            if (!inline) {
                checked = ' checked="checked" ';
                name = '"on"';
            }
            if(valid) {
            	cell2.innerHTML = '<input type="checkbox" name=' + name + ' onclick="handleClick(this);"' + checked + '/>';
            	cell2.className = 'selected';
            }

            if (i % 2) {// For alternating row colours
                cell1.className = 'greyCell';
                cell2.className = 'greyCell';
            }
        }

        var attachmentDetailsDiv = document.getElementById('attachmentDetails');
        attachmentDetailsDiv.style.display = "block";

        var attachmentDiv = document.getElementById('attachmentDetails');
        var attachmentTableDiv = document.createElement("div");
        attachmentTableDiv.setAttribute('id', 'attachmentTable');
        attachmentTableDiv.appendChild(table);
        attachmentDiv.appendChild(attachmentTableDiv);
    }
}

function filedResponse(obj) {
    var div = document.getElementById('jobnumbers');

    if (obj.errors != '') {
        div.innerHTML = 'Server error - unable to retrieve status';
        document.getElementById("statusImg").style.visibility = "hidden";
    }
    else {
        document.getElementById("statusImg").style.visibility = "visible";
        updateFiledStatusIcon(obj);

        var response = gadgets.json.parse(obj.data);

        div.innerHTML = response.filedStatus;

        addAttachmentFilenamesToTable(response);

        var jobNumberTextField = document.getElementById('inputbox');
        jobNumberTextField.value = response.jobNumbers;

        setFileComponentsVisibility(true);
    }
}

function updateFiledStatusIcon(obj) {
    if (obj.data.indexOf('Not Filed') > -1) {
        document.getElementById("statusImg").src = gadgets.io.getProxyUrl("http://test-oscar-gmail-gadget.googlecode.com/svn/trunk/remove.gif");
    }
    else {
        document.getElementById("statusImg").src = gadgets.io.getProxyUrl("http://test-oscar-gmail-gadget.googlecode.com/svn/trunk/greenTick.gif");
    }
}

function fileAgainstJobResponse(obj) {
    var jobno = getJobNumberText();
    var paragraph = document.getElementById('validationResponse');
    if (obj.text != '') {
        paragraph.innerHTML = obj.text;
    }
    else if(obj.errors != '') {
    	if(obj.rc == '504') {    		
    		paragraph.innerHTML = 'File request received';
    	}
    	else {
    		paragraph.innerHTML = 'Server error: Unable to process request';
    	}
    }
    else {
    	paragraph.innerHTML = 'Filed Successfully';
    	
    	var newJobNumbers = addJobToFiledStatusAndSort(jobno);
    	
    	var div = document.getElementById('jobnumbers');
    	div.innerHTML = newJobNumbers;
    	updateFiledStatusIcon({data: newJobNumbers});
    }

    setFileComponentsVisibility(true);
}

function setAllAttachmentSelectionTo(selected) {
    var table = document.getElementById('tblAttachments');

    for (var i = 0; i < table.rows.length; i++) {
        var row = table.rows[i];
        if(row.cells[1].innerHTML.lastIndexOf('<input', 0) != 0) {
        	continue;
        }
        if (selected) {
            row.cells[1].innerHTML = '<input type="checkbox" checked="checked" name="on" onclick="handleClick(this);"/>';
        }
        else {
            row.cells[1].innerHTML = '<input type="checkbox" name="off" onclick="handleClick(this);"/>';
        }
    }
}

function addJobToFiledStatusAndSort(jobno) {
    var div = document.getElementById('jobnumbers');
    var jobNumbers = div.innerHTML.split(',');
    if (jobNumbers[0] == 'Not Filed') {
        jobNumbers.splice(0, 1);
    }
    jobNumbers.push(jobno);
    jobNumbers.sort(function(a, b) {
        return a - b;
    });
    return jobNumbers;
}

function makeCachedRequest(url, callback, params, refreshInterval) {
    var ts = new Date().getTime();
    var sep = "?";
    if (refreshInterval && refreshInterval > 0) {
        ts = Math.floor(ts / (refreshInterval * 1000));
    }
    if (url.indexOf("?") > -1) {
        sep = "&";
    }
    url = [ url, sep, "nocache=", ts ].join("");
    gadgets.io.makeRequest(url, callback, params);
}

function autoDetectSite() {
    var params = {};
    var encodedEmail = encodeURIComponent(loggedInUsersEmail);
    var url = baseUri + 'oscarfiler/file/detectsite/email/' + encodedEmail;

    gadgets.io.makeRequest(url, autoDetectSiteResponse, params);
}

function autoDetectSiteResponse(obj) {
    var div = document.getElementById('siteCode');
    if (obj.errors != '') {
        div.innerHTML = 'Server error - unable to retrieve site code';
    }
    else {
        gadgets.window.adjustHeight();
        div.innerHTML = obj.data;
        var jobNoTextField = document.getElementById('inputbox');
        if (div.innerHTML == 'undefined') {
            jobNoTextField.value = '';
            var paragraph = document.getElementById('validationResponse');
            paragraph.innerHTML = '';
            var jobnodiv = document.getElementById('jobnumbers');
            jobnodiv.innerHTML = '';
            document.getElementById("statusImg").src = null;
        }
        else {
            jobNoTextField.value = 'Determining job numbers...';
            checkFiledStatus();
        }
    }
}

function setFileComponentsVisibility(visible) {
    document.getElementById("button").disabled = !visible;
    document.getElementById('inputbox').readOnly = !visible;
}

function checkUserLoggedIn() {
    //Gets all data from the email that was extracted and stores it in matches array.
    var matches = google.contentmatch.getContentMatches();
    messageID = getMessageIDFromExtractorMatches(matches);

    var jobNoTextField = document.getElementById('inputbox');
    setFileComponentsVisibility(false);

    jobNoTextField.onkeypress = function() {
        var paragraph = document.getElementById('validationResponse');
        if (document.getElementById('inputbox').readOnly == false) {
            paragraph.innerHTML = '';
        }
    };

    //Read from user prefs and set loggedInUser
    loggedInUsersEmail = getEmailAddressFromCache();

    if (loggedInUsersEmail !== '') {
        document.getElementById('emailaddr').value = loggedInUsersEmail;
        autoDetectSite();
    }

    gadgets.window.adjustHeight();
}

function getEmailAddressFromCache() {
    var prefs = new _IG_Prefs();
    return prefs.getString('email');
}

function setEmailAddress() {
    setFileComponentsVisibility(false);
    loggedInUsersEmail = document.getElementById('emailaddr').value;
    var prefs = new _IG_Prefs();
    prefs.set('email', loggedInUsersEmail);
    autoDetectSite();
}

gadgets.util.registerOnLoadHandler(checkUserLoggedIn);